﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinqToTwitter;

namespace Genesis.Application
{
    public static class LinqToTwitterWrapper
    {
        public static TwitterContext twitterCtx = new TwitterContext(Globals.auth, "https://api.twitter.com/1/", "http://search.twitter.com/");

        public static void SignOn()
        {
            if (twitterCtx.AuthorizedClient is OAuthAuthorization)
            {
                InitializeOAuthConsumerStrings(twitterCtx);
            }

            try
            {
                Globals.auth.SignOn();
            }
            catch (OperationCanceledException)
            {
                return;
            }
        }

        public static void UpdateStatus(string Tweet)
        {
            twitterCtx.UpdateStatus(Tweet);
        }

        public static LinqToTwitter.TwitterQueryable<LinqToTwitter.Status> GetPublicTweets()
        {
            var tweets =
                from tweet in twitterCtx.Status
                where tweet.Type == (Globals.auth.CachedCredentialsAvailable ? StatusType.Friends : StatusType.Public)
                orderby tweet.CreatedAt ascending
                select tweet;

            return (LinqToTwitter.TwitterQueryable<LinqToTwitter.Status>)tweets;
        }

        private static void InitializeOAuthConsumerStrings(TwitterContext twitterCtx)
        {
            var oauth = (DesktopOAuthAuthorization)twitterCtx.AuthorizedClient;
            oauth.GetVerifier = () =>
            {
                return Genesis.Application.Forms.Verifier.GetVerificationPin();
            };

            if (oauth.CachedCredentialsAvailable)
            {
                Console.WriteLine("Skipping OAuth authorization step because that has already been done.");
            }
        }
    }
}
